import imp, stackless
import generative
from string import *
import re
import sys, numpy
from xml.dom.minidom import parse
b={}
from pyparsing import *
objs=[]
charset=[[["="]],[["[","]"],["{", "}"]],[["(",")"],["'","'"],[">"],["<"],["-"]],[["\\"],["#"],["%"],["."]],[["v"], ["s"], ["|"]]]

def parsestr(astring, ix=0):
        punctuation=[]
        alist=[]
        digits = "0123456789*"
        number = Word( digits )
        try:
                for i in charset[len(charset)-(ix+1)]:
                               punctuation.append(Optional(i[0])+number if len(i)==1 else Optional(i[0])+ number+ Optional(i[1]))
                grammar=And( punctuation )
                def replace(seq):
                          for data in seq:
                                try:
                                        astring.replace(data,"*")
                                        alist.append(data)
                                except TypeError:
                                        if isinstance(data,int):
                                                astring.replace(str(data),"*")
                                                alist.append(str(data))
                                        else:
                                                replace(data)
                replace(grammar.scanString(astring))
                objs.append(alist)
                parsestr(astring, ix+1)
        except IndexError:
                return 
def squeeze(input_file):
        doc=parse(input_file)
       
        
        
        max_halt=doc.getElementsByTagName("loop")[0].childNodes[0].nodeValue
        code=[]
        c=doc.getElementsByTagName("command")
        for i in c:
                for counter in xrange(len(i.childNodes)):
                        j=i.childNodes[counter]
                        if j.nodeType!=3:
                                inp=j.childNodes[0].nodeValue
                                if inp!="....":
                                        k=j.nodeName
                                        if k=="val":
                                                code.append(inp.split(":")[0])
					        del j
	ci=0
        while(ci<max_halt):
                k=generative.main(input_file)
                stackless.run()
		ux=k.data.pop()
		root=ux.root
                number=root.number                
                code=join(["s1=[%s]-[.s%i-%i]!"%(join(code,'&'),i,numpy.sum(number[i])) for i in xrange(number.shape[0])])
		input_file=('<?xml version="1.0" encoding="UTF-8"?>\n<command>\n\t<loop>%i</loop>\n\t<desc>%s,%f,%f</desc>\n\t<val>%s</val>\n</command>'%(ci,ux.stream, root.timestep, root.cellwidth, code))
		ci+=1

        f=open("code.dat")
        f.write("code")
	
if __name__=='__main__':
        squeeze(sys.argv[1])

